<template>
  <div>
    <div ref="container"></div>
  </div>
</template>

<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
export default {
  name: "HomeView",
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      model: null,
      controls: null,
      width: window.innerWidth,
      height: window.innerHeight,
    };
  },
  mounted() {
    this.initThreeJs();
    this.loadModel();
    this.animate();
  },
  beforeDestroy() {
    if (this.renderer) {
      this.renderer.dispose();
    }
  },
  methods: {
    initThreeJs() {
      // 初始化场景
      this.scene = new THREE.Scene();
      // this.scene.background = new THREE.Color(0xffffff); // 白色背景
      // 设置相机
      this.camera = new THREE.PerspectiveCamera(75, this.width / this.height, 0.1, 5000);
      // 设置相机初始位置
      this.camera.position.set(0, 0.3, 1); // x = 0, y = 5, z = 10，可以根据需要调整这些值

      // 设置相机旋转角度（以弧度为单位）
      this.camera.rotation.x = THREE.MathUtils.degToRad(-30); // 绕x轴旋转 -30度
      this.camera.rotation.y = THREE.MathUtils.degToRad(0); // 绕y轴旋转 0度
      this.camera.rotation.z = THREE.MathUtils.degToRad(0); // 绕z轴旋转 0度

      // 创建渲染器
      this.renderer = new THREE.WebGLRenderer();
      this.renderer.setSize(this.width, this.height);
      this.$refs.container.appendChild(this.renderer.domElement);

      // 添加灯光
      const ambientLight = new THREE.AmbientLight(0xffffff, 1);
      this.scene.add(ambientLight);

      const pointLight = new THREE.PointLight(0xffffff, 1);
      pointLight.position.set(10, 10, 10);
      this.scene.add(pointLight);

      // 添加 OrbitControls
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true; // 启用阻尼
      this.controls.dampingFactor = 0.25; // 阻尼因子，越大越慢
      this.controls.enableZoom = true; // 启用缩放
    },
    loadModel() {
      const loader = new GLTFLoader();
      loader.load(
          '/obj.gltf', // 模型的路径，支持http请求
          (gltf) => {
            this.model = gltf.scene;
            this.scene.add(this.model);
          },
          undefined,
          (error) => {
            console.error('模型加载错误:', error);
          }
      );
    },
    animate() {
      requestAnimationFrame(this.animate);
      if (this.model) {
        this.model.rotation.y += 0.01; // 让模型旋转
      }
      this.renderer.render(this.scene, this.camera);
    },
  }
};
</script>

<style scoped lang="scss">

</style>

